import CompanyForm from '@/components/CompanyForm/CompanyForm.vue'
import {
    pageListCompanyApi,
    addCompanyApi,
    updateCompanyApi,
    deleteCompanyApi,
    getCompanyByIdApi
} from '@/api/Company'

export default {
    name: 'CompanyPage',
    components: {CompanyForm},
    data() {
        return {
            // 公司列表数据
            companyList: [],
            // 加载状态
            loading: false,
            // 搜索栏关键词
            searchKeyword: '',
            // 分页信息
            pagination: {
                current: 1,
                size: 10,
                total: 0
            },
            // 对话框相关
            dialogVisible: false,
            dialogTitle: '新增公司',
            formData: {}
        }
    },
    mounted() {
        this.fetchCompanyList();
    },
    methods: {

        // 获取公司列表
        async fetchCompanyList() {
            this.loading = true;
            try {
                const response = await pageListCompanyApi(this.pagination.current, this.pagination.size, this.searchKeyword);
                const data = response.data;
                this.companyList = data.list || [];
                this.pagination.total = data.total || 0;
            } catch (error) {
                console.error('获取公司列表失败:', error);
                this.$message.error(error.message || '获取公司列表失败');
            } finally {
                this.loading = false;
            }
        },
        // 处理搜索
        handleSearch() {
            this.pagination.current = 1;
            this.fetchCompanyList();
        },
        // 处理分页大小变化
        handleSizeChange(size) {
            this.pagination.size = size;
            this.fetchCompanyList();
        },

        // 处理当前页变化
        handleCurrentChange(current) {
            this.pagination.current = current;
            this.fetchCompanyList();
        },

        // 打开新增对话框
        handleAdd() {
            this.dialogTitle = '新增公司';
            this.formData = {
                id: null,
                name: '',
                establishmentDate: '',
                registeredCapital: 0,
                operating: true
            }
            this.dialogVisible = true;
        },

        // 打开编辑对话框
        async handleEdit(row) {
            this.dialogTitle = '编辑公司';
            const loadingInstance = this.$loading();
            try {
                // 获取公司详情
                const response = await getCompanyByIdApi(row.id);
                const companyDetails = response.data;

                this.formData = {...companyDetails}
                this.dialogVisible = true;
            } catch (error) {
                console.error('获取公司详情失败:', error);
                this.$message.error(error.message || '获取公司详情失败');
            } finally {
                // 关闭加载状态
                loadingInstance.close();
            }
        },

        // 处理表单提交
        async handleFormSubmit(formData) {
            try {
                if (formData.id) {
                    // 更新公司信息
                    await updateCompanyApi(formData)
                    this.$message.success('更新成功')
                } else {
                    //添加公司信息
                    await addCompanyApi(formData)
                    this.$message.success('添加成功')
                }
                this.dialogVisible = false
                await this.fetchCompanyList()
            } catch (error) {
                this.$message.error(error.message || '操作失败')
            }
        },


        // 删除公司
        handleDelete: function (id) {
            this.$confirm('确定要删除该公司吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                try {
                    await deleteCompanyApi(id);
                    this.$message.success('删除成功');
                    await this.fetchCompanyList();
                } catch (error) {
                    console.error('删除失败:', error);
                    this.$message.error(error.message || '删除失败');
                }
            }).catch(() => {
            });
        },

        // 重置表单数据
        resetFormData() {
            this.formData = {
                id: null,
                name: '',
                establishmentDate: '',
                registeredCapital: 0,
                operating: true
            }
        },

        // 格式化日期
        formatDate(dateString) {
            if (!dateString) return '';
            const date = new Date(dateString);
            return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
        },

        // 格式化资本
        formatCapital(capital) {
            if (capital === null || capital === undefined) return '0.00';
            return capital.toLocaleString('zh-CN', {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2
            });
        }
    }
}
